package problem2_Add_Two_Numbers;

public class MySolution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode current = null;
		int bonus = 0;
		ListNode head = null;
		while (l1 != null && l2 != null) {
			int sum = l1.val + l2.val + bonus;
			ListNode node;
			if (sum <= 9) {
				node = new ListNode(sum);
				bonus=0;
			} else {
				bonus = 1;
				node = new ListNode(sum - 10);
			}
			if (head == null) {
				head = node;
			} else {
				current.next = node;
			}
			current = node;
			l1 = l1.next;
			l2 = l2.next;
		}
		if (l1 == null && l2 != null) {
			if (bonus == 1) {
				ListNode node = new ListNode(1);
				current.next = addTwoNumbers(node, l2);
			} else {
				while(l2!=null){
					current.next=l2;
					l2=l2.next;
					current=current.next;
				}
			}
		}else if(l2==null&&l1!=null){
			if (bonus == 1) {
				ListNode node = new ListNode(1);
				current.next = addTwoNumbers(node, l1);
			} else {
				while(l1!=null){
					current.next=l1;
					l1=l1.next;
					current=current.next;
				}
			}
		}else{
			if(bonus==1){
				ListNode node = new ListNode(1);
				current.next = node;
			}
		}
		return head;
	}

	public class ListNode {
		int val;
		ListNode next;

		public ListNode(int val) {
			super();
			this.val = val;
		}
	}

	public static void main(String[] args) {
		MySolution solution = new MySolution();
		ListNode l1 = solution.new ListNode(2);
		ListNode l2 = solution.new ListNode(4);
		ListNode l3 = solution.new ListNode(3);
		l1.next = l2;
		l2.next = l3;
		ListNode l4 = solution.new ListNode(5);
		ListNode l5 = solution.new ListNode(6);
		ListNode l6 = solution.new ListNode(4);
		l4.next = l5;
		l5.next = l6;
		ListNode result = solution.addTwoNumbers(l1, l4);
		while (result != null) {
			System.out.print(result.val + (result.next != null ? "->" : ""));
			result = result.next;
		}
	}

}
